package com.henry.imkit.network

import java.security.SecureRandom
import javax.net.ssl.*

object SSLSocketFactoryUtils {

    // 获取SSLSocketFactory
    fun getSSLSocket(): SSLSocketFactory? {
        return try {
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, getTrustManager(), SecureRandom())
            sslContext.socketFactory
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    // 获取所有TrustManager
    fun getTrustManager(): Array<X509TrustManager> {
        return arrayOf<X509TrustManager>(object : X509TrustManager {
            override fun checkClientTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun checkServerTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                return arrayOf()
            }
        })
    }

    // 获取X509TrustManager
    fun getX509TrustManager(): X509TrustManager? {
        return getTrustManager()?.get(0)
    }

    // 获取HostnameVerifier
    fun getHostnameVerifier(): HostnameVerifier? {
        return HostnameVerifier { _, _ -> true }
    }

    /**
     * Glide加载Https图片失败, 不应用glide:okhttp3-integration有效
     * 在Application中的OnCreate()方法中调用该方法
     *
     * 如何使用glide:okhttp3-integration请新建BaseGlide，重写AppGlideModule
     */
    fun handleSSLHandshake() {
        try {
            val trustAllCerts = getTrustManager()
            val sc = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)
            HttpsURLConnection.setDefaultHostnameVerifier { hostname, session -> true }

        } catch (ignored: java.lang.Exception) {
        }
    }

}